package com.rzdata.poct.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rzdata.poct.common.core.mybatisplus.core.ServicePlusImpl;
import com.rzdata.poct.common.core.page.PagePlus;
import com.rzdata.poct.common.core.page.TableDataInfo;
import com.rzdata.poct.common.utils.PageUtils;
import com.rzdata.poct.common.utils.StringUtils;
import com.rzdata.poct.system.domain.business.bo.PoctDetectionResultBo;
import com.rzdata.poct.system.domain.business.po.PoctDetectionItems;
import com.rzdata.poct.system.domain.business.po.PoctDetectionResult;
import com.rzdata.poct.system.domain.business.vo.PoctDetectionResultVo;
import com.rzdata.poct.system.domain.business.vo.PoctDetectionRulesVo;
import com.rzdata.poct.system.domain.business.vo.PoctProjectTestitemsVo;
import com.rzdata.poct.system.mapper.PoctDetectionResultMapper;
import com.rzdata.poct.system.service.IPoctDetectionItemsService;
import com.rzdata.poct.system.service.IPoctDetectionResultService;
import com.rzdata.poct.system.service.IPoctDetectionRulesService;
import com.rzdata.poct.system.service.IPoctProjectTestitemsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * POCT检测结果Service业务层处理
 *
 * @author ruoyi
 * @date 2021-09-09
 */
@Service
public class PoctDetectionResultServiceImpl extends ServicePlusImpl<PoctDetectionResultMapper, PoctDetectionResult, PoctDetectionResultVo> implements IPoctDetectionResultService {

    @Autowired
    IPoctDetectionItemsService iPoctDetectionItemsService;

    @Autowired
    IPoctDetectionRulesService iPoctDetectionRulesService;

    @Override
    public PoctDetectionResultVo queryById(Long id){
        return getVoById(id);
    }

    @Override
    public TableDataInfo<PoctDetectionResultVo> queryPageList(PoctDetectionResultBo bo) {
        PagePlus<PoctDetectionResult, PoctDetectionResultVo> result =
            pageVo(PageUtils.buildPagePlusNew(Long.valueOf(bo.getPageNum()), Long.valueOf(bo.getPageSize())), buildQueryWrapper(bo));
        return PageUtils.buildDataInfo(result);
    }

    @Override
    public List<PoctDetectionResultVo> queryList(PoctDetectionResultBo bo) {
        return listVo(buildQueryWrapper(bo));
    }

    private LambdaQueryWrapper<PoctDetectionResult> buildQueryWrapper(PoctDetectionResultBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<PoctDetectionResult> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getDetectionNo()), PoctDetectionResult::getDetectionNo, bo.getDetectionNo());
        lqw.eq(bo.getProjectId() != null, PoctDetectionResult::getProjectId, bo.getProjectId());
        lqw.like(StringUtils.isNotBlank(bo.getProjectName()), PoctDetectionResult::getProjectName, bo.getProjectName());
        lqw.ge(bo.getDetectionTime() != null, PoctDetectionResult::getDetectionTime, bo.getDetectionTime());
        lqw.like(StringUtils.isNotBlank(bo.getPatientName()), PoctDetectionResult::getPatientName, bo.getPatientName());
        lqw.eq(StringUtils.isNotBlank(bo.getGender()), PoctDetectionResult::getGender, bo.getGender());
        lqw.eq(StringUtils.isNotBlank(bo.getAge()), PoctDetectionResult::getAge, bo.getAge());
        lqw.eq(StringUtils.isNotBlank(bo.getBirthday()), PoctDetectionResult::getBirthday, bo.getBirthday());
        lqw.eq(StringUtils.isNotBlank(bo.getCaseNumber()), PoctDetectionResult::getCaseNumber, bo.getCaseNumber());
        lqw.eq(StringUtils.isNotBlank(bo.getAttendingDoctor()), PoctDetectionResult::getAttendingDoctor, bo.getAttendingDoctor());
        lqw.eq(StringUtils.isNotBlank(bo.getDoctorPost()), PoctDetectionResult::getDoctorPost, bo.getDoctorPost());
        lqw.eq(StringUtils.isNotBlank(bo.getDetectionSample()), PoctDetectionResult::getDetectionSample, bo.getDetectionSample());
        lqw.eq(bo.getDeptId() != null, PoctDetectionResult::getDeptId, bo.getDeptId());
        lqw.like(StringUtils.isNotBlank(bo.getDeptName()), PoctDetectionResult::getDeptName, bo.getDeptName());
        lqw.like(StringUtils.isNotBlank(bo.getSpecimenNo()), PoctDetectionResult::getSpecimenNo, bo.getSpecimenNo());
        lqw.like(StringUtils.isNotBlank(bo.getInstrumentName()), PoctDetectionResult::getInstrumentName, bo.getInstrumentName());
        lqw.like(StringUtils.isNotBlank(bo.getInstrumentNo()), PoctDetectionResult::getInstrumentNo, bo.getInstrumentNo());
        lqw.eq(StringUtils.isNotBlank(bo.getInspector()), PoctDetectionResult::getInspector, bo.getInspector());
        lqw.eq(StringUtils.isNotBlank(bo.getDiagnostic()), PoctDetectionResult::getDiagnostic, bo.getDiagnostic());
        lqw.eq(bo.getType() != null, PoctDetectionResult::getType, bo.getType());
        lqw.eq(StringUtils.isNotBlank(bo.getDoctorsAdvice()), PoctDetectionResult::getDoctorsAdvice, bo.getDoctorsAdvice());
        lqw.eq(StringUtils.isNotBlank(bo.getResult()), PoctDetectionResult::getResult, bo.getResult());
        lqw.eq(bo.getReportTime() != null, PoctDetectionResult::getReportTime, bo.getReportTime());
        lqw.eq(bo.getSamplingTime() != null, PoctDetectionResult::getSamplingTime, bo.getSamplingTime());
        lqw.eq(bo.getReceiveTime() != null, PoctDetectionResult::getReceiveTime, bo.getReceiveTime());
        lqw.eq(bo.getPatientTime() != null, PoctDetectionResult::getPatientTime, bo.getPatientTime());
        lqw.eq(ObjectUtil.isNotEmpty(bo.getStatus()), PoctDetectionResult::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getPatientCreator()), PoctDetectionResult::getPatientCreator, bo.getPatientCreator());
        return lqw;
    }

    @Override
    public Boolean insertByBo(PoctDetectionResultBo bo) {
        PoctDetectionResult add = BeanUtil.toBean(bo, PoctDetectionResult.class);
        add.setCreateTime(new Date());
        add.setStatus(0);
        add.setPatientTime(new Date());
        validEntityBeforeSave(add);
        boolean result = save(add);
        // 保存检验项
        saveItems(add, bo.getDetectionValue());
        return result;
    }

    private void saveItems(PoctDetectionResult poctDetectionResult, String detectionValue) {
        if (ObjectUtil.isNotEmpty(poctDetectionResult)) {
            PoctDetectionItems poctDetectionItems = new PoctDetectionItems();
            poctDetectionItems.setDetectionId(poctDetectionResult.getId());
            PoctDetectionRulesVo vo = iPoctDetectionRulesService.queryByItemId(poctDetectionResult.getProjectId());
            if (ObjectUtil.isNotEmpty(vo)) {
                poctDetectionItems.setItemId(vo.getItemId());
                poctDetectionItems.setItemName(vo.getItemName());
                poctDetectionItems.setItemEname(vo.getItemEname());
                poctDetectionItems.setUnit(vo.getUnit());
//                poctDetectionItems.setDetectionMethod();
                poctDetectionItems.setDetectionValue(detectionValue);
                String str = "";
                if (ObjectUtil.isNotEmpty(vo.getMinnormalValue())) {
                    str = vo.getMinnormalValue();
                }
                if (ObjectUtil.isNotEmpty(vo.getMaxnormalValue())) {
                    str += str + "-" + vo.getMaxnormalValue();
                }
                poctDetectionItems.setReferenceValue(str);
            }
            iPoctDetectionItemsService.save(poctDetectionItems);
        }
    }

    @Override
    public Boolean updateByBo(PoctDetectionResultBo bo) {
        PoctDetectionResult update = BeanUtil.toBean(bo, PoctDetectionResult.class);
        validEntityBeforeSave(update);
        updateItems(update, bo.getDetectionValue());
        return updateById(update);
    }

    private void updateItems(PoctDetectionResult poctDetectionResult, String detectionValue) {
        if (ObjectUtil.isNotEmpty(poctDetectionResult)) {
            QueryWrapper<PoctDetectionItems> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(PoctDetectionItems:: getDetectionId, poctDetectionResult.getId());
            List<PoctDetectionItems> itemsList = iPoctDetectionItemsService.list(queryWrapper);
            if (ObjectUtil.isNotEmpty(itemsList)) {
                iPoctDetectionItemsService.removeByIds(itemsList.stream().map(x -> x.getId()).collect(Collectors.toList()));
            }
            PoctDetectionItems poctDetectionItems = new PoctDetectionItems();
            poctDetectionItems.setDetectionId(poctDetectionResult.getId());
            PoctDetectionRulesVo vo = iPoctDetectionRulesService.queryByItemId(poctDetectionResult.getProjectId());
            if (ObjectUtil.isNotEmpty(vo)) {
                poctDetectionItems.setItemId(vo.getItemId());
                poctDetectionItems.setItemName(vo.getItemName());
                poctDetectionItems.setItemEname(vo.getItemEname());
                poctDetectionItems.setUnit(vo.getUnit());
//                poctDetectionItems.setDetectionMethod();
                poctDetectionItems.setDetectionValue(detectionValue);
                String str = "";
                if (ObjectUtil.isNotEmpty(vo.getMinnormalValue())) {
                    str = vo.getMinnormalValue();
                }
                if (ObjectUtil.isNotEmpty(vo.getMaxnormalValue())) {
                    str += str + "-" + vo.getMaxnormalValue();
                }
                poctDetectionItems.setReferenceValue(str);
            }
            iPoctDetectionItemsService.save(poctDetectionItems);
        }
    }
    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(PoctDetectionResult entity){
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return removeByIds(ids);
    }
}
